<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/12/13
 * Time: 下午3:05
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\track\XhtrackTask;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\phpmailerException;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\Power;
use Modules\School;
use Phalcon\Exception;
use Services\App;
use Services\Feedback;
use function Sodium\library_version_major;

class FeedbackController extends ControllerBase
{

    private $assessment =[
        1 => '满意',
        2 => '不满意'
    ];

    private $feedbackType = [
        1 => '产品建议',
        2 => '程序错误',
        3 => '运营建议',
        4 => '资料错误',
        5 => '其他',
    ];

    private $replyStatus =[
        1 => '已回复',
        2 => '未回复'
    ];


    public static $enum = [
        'assessment'  => [0 => '默认', 1 => '满意', 2 => '不满意'],
        'replyStatus' => [0 =>'未回复', 1 => '已回复',2 => '已解决',3 => '已结束'],
        'feedbackType' => [1 => '产品建议', 2 => '程序错误',  3 => '运营建议', 4 => '资料错误', 5 => '其他'],
        'userType'     => [0 => '', 1 => '学生', 4 => '老师'],
    ];

    public static $operate = [0 => '状态',1 => '未回复', 2 => '已回复', 3 => '已解决', 4 => '已结束'];



    /**
     * 返回错误信息
     * @param $response
     * @param string $replaceError
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180330
     * modify by dale 20180822  弃用
     */
    public function showError($response, $replaceError = '接口错误')
    {
        $err  = $response->toArray();
        if (isset($err['msg'])) {
            $errMsg = $err['msg'];
        } elseif ($err['message']) {
            $errMsg = $err['message'];
        } else {
            $errMsg = $replaceError;
        }
        return $this->sendErrorResponse(500, $errMsg, json_encode($err));
    }



    /**
     * 反馈列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20180822
     */
    public function indexAction()
    {
        try {
            if (!Power::exist('App_Feedback')) {
                return $this->sendViewError('没有权限');
            }
//            $this->view->setTemplateBefore('listForm');
            $this->view->pick('feedback/index');
            Assets::easyUI('', true);
            Assets::importJs('js/feedback/index.js');
            Template::exists('Feedback_List', 'list')
            or die(Main::showMessageModal('Feedback_List配置文件不存在，请先创建！', 109106002));
            $listButtonArr = $formButtonArr = $listSearchArr = array();
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_seeTemplate', 'text' => '回复模板',
                'icon' => 'fa-eye');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_seeShieldList', 'text' => '禁言列表',
                'icon' => 'fa-eye');
            if (Power::exist('App_Feedback_Reply')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_apply', 'text' => '批量回复',
                    'icon' => 'fa-commenting-o');
            }
            if (Power::exist('App_Feedback_Shield')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_shield', 'text' => '禁言',
                    'icon' => 'fa-minus-circle');
            }
            if (Power::exist('App_Feedback_Del')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除',
                    'icon' => 'fa-trash');
            }
            $schools = School::getPower(true);
            if ($schools === true) {
                $schools = School::getSchools();
            }
            $areaEnum = array_column(Hrm::getDepArray('XHYYB', 1), 'text', 'id');
//            $listSearchArr[] = array('type' => 'text', 'class'  => 'easyui-datebox', 'id' => 'search_startTime',
//                'label' => ' 时间段：','style'=>'width:100px!important;',
//                'value' => date('Y-m-d', strtotime(date('Y-m', time()))) );
            $listSearchArr[] = array('type' => 'text', 'class'  => 'easyui-datebox', 'id' => 'search_startTime',
                'label' => ' 时间段：','style'=>'width:100px!important;',
                'value' => '2018-10-01' );
            $listSearchArr[] = array('type' => 'text', 'class' => 'easyui-datebox', 'id' => 'search_endTime',
                'label' => ' ~ ', 'style' => 'width:100px!important;', 'value' => date('Y-m-d'));
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_area',
                'data' => $areaEnum + [0 => '全部区']  , 'default' => '0','style' => 'width:100px!important;' );
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_city',
                'data' =>  [0 => '全部市'], 'default' => '0','style' => 'width:100px!important;' );
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_schools',
                'data' =>  [0 => '请选择学校'] + $schools, 'default' => '0','style' => 'width:140px;' );
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_userType',
                'data' => [0 => '用户类型' , 1 => '学生', 4 => '老师'], 'default' => '','style' => 'width:80px;');
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_packageName',
                'data' => $this->AppMatch(), 'default' => '0','style' => 'width:140px;');
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_status',
                'data' => self::$operate, 'default' => '0','style' => 'width:80px!important;');
            $listSearchArr[] = array('type' => 'select', 'id' => 'list_search_type', 'data' => [1 => '提问人', 2 => '内容'],
                'default' => '1','style' => 'width:80px!important;');
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => '');
            $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search',
                'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
            return $this->view->setVars([
                'List'       => Template::createList('list', 'Feedback_List', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
                ]),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e instanceof XhException ? $e->getDescription() : $e->getMessage());
        }
    }

    /**
     * 回复面板
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20190118
     */
    public function replyPanelAction()
    {
        try {
            $id = $this->request->getQuery('id', 'string');
            if (!$id) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('feedback/replyPanel');
            Assets::select2();
            Assets::importJs('js/feedback/replyPanel.js');
            $row = Feedback::getFeedbackDetail($id);
            $row['createTime'] = date('Y-m-d H:i:s', $row['createTime'] / 1000);
            $row['nowStatus'] = self::$enum['replyStatus'][$row['replyStatus']];
            $loginName = XhsysUser::getUserLogonName([ 0 => $row['userId']])[$row['userId']];
            $row['name'] = $row['userName'];
            $row['userName'] =  $row['userName'] .' (' . self::$enum['userType'][$row['userType']] . '-'. $loginName .' )';
            if ($row['forbidStatus']) {
                $row['userName'] =  $row['userName'] .'<i class="fa fa-ban" style="color: red;"></i>';
            }
            $row['userType'] = self::$enum['userType'][$row['userType']];
            if ($row['solveTime']) {
                $row['solveTime'] = date('Y-m-d H:i:s', $row['solveTime'] / 1000);
            } else {
                $row['solveTime'] = '';
            }
            $row['feedbackType'] = self::$enum['feedbackType'][$row['feedbackType']];
            foreach ($row['replyContent'] as &$contentRow) {
                $contentRow['createTime'] = date('Y-m-d H:i:s', $contentRow['createTime'] / 1000);
            }
            return $this->view->setVars([
                'info' => $row,
                'templates' => Tool::getValue(Feedback::getTemplateList(), 'data', []),
                'replyPower' => Power::exist('App_Feedback_Reply'),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }


    /**
     * 获取反馈信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180823
     * modify by dale 20190111  开始时间 结束时间  schoolId 数组
     */
    public function getFeedbackAction()
    {
        try {
            $page = $this->request->getPost('page', 'int');
            $rows = $this->request->getPost('rows', 'int');
            $schoolId = $this->request->getPost('schoolId', 'int');
            $userType = $this->request->getPost('userType', 'int');
            $operate = $this->request->getPost('operate', 'int');
            $key = $this->request->getPost('key', 'string');
            $packageName = $this->request->getPost('packageName', 'string');
            $startTime = $this->request->getPost('startTime', 'string');
            $endTime   = $this->request->getPost('endTime', 'string');
            $area = $this->request->getPost('area', 'string');
            $city = $this->request->getPost('city', 'string');
            $searchType = $this->request->getPost('searchType', 'int');
            $params = [];
            if ($schoolId) {
                $params['schoolIds'] = [$schoolId];
            } else {
                $userId = Main::getLoginUserInfo('userId');
                if (!$area && !$city) {  //没有选中区域
                    $schools = User::getSchoolPower(true, $userId);
                } else { //只选中区
                    if ($area && !$city) {
                        $areaId = $area;
                    } elseif ($area && $city) {
                        $areaId = $city;
                    }
                    $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$areaId},%'"; //取第一个
                    $staffs = $this->db->fetchOne($staffSql);
                    $schools = User::getSchool(true, $staffs['iUserId'], true);
                }
                $params['schoolIds'] = array_keys($schools);
            }
            if ($params['schoolIds']) {
                foreach ($params['schoolIds'] as &$row) {
                    $row = intval($row);
                }
                unset($row);
            }

            if ($userType) {
                $params['userType'] = $userType;
            }
            if ($operate) {
                $params['replyStatus'] = $operate - 1;
            }
            if ($packageName) {
                $params['packageName'] = $packageName;
            }
            if ($key) {
                $params['searchContent'] = $key;
            }
            if ($searchType) {
                $params['searchType'] = $searchType;
            }
            if ($startTime) {
                $params['startTime'] = strtotime($startTime) *1000;
            } else {
//                $params['startTime'] = strtotime(date('Y-m', time())) * 1000;
                $params['startTime'] = strtotime('2018-10-01') * 1000;
            }
            if ($endTime) {
                $params['endTime'] = strtotime($endTime.' 23:59:59') *1000;
            } else {
                $params['endTime'] = time() * 1000;
            }
//            var_dump($params);die;
            $data = Feedback::getFeedbackList($page, $rows, $params);
            Tool::runEnum($data['rows'], self::$enum);
            foreach ($data['rows'] as &$row) {
                $row['createTime'] = date('Y-m-d H:i:s', $row['createTime'] / 1000);
                if ($row['updateTime']) {
                    $row['updateTime'] = date('Y-m-d H:i:s', $row['updateTime'] / 1000);
                } else {
                    $row['updateTime'] = '';
                }
                if ($row['replyTime']) {
                    $row['replyTime'] = date('Y-m-d H:i:s', $row['replyTime'] / 1000);
                } else {
                    $row['replyTime'] = '';
                }
                $row['nowStatus'] = $row['replyStatus'];
                if ($row['forbidStatus']) {
                    $row['userName'] = $row['userName'] . '<i class="fa fa-ban" style="color: red;"></i>';
                }
            }
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * ajax获取app信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180823 id
     */
    public function ajaxGetAppAction()
    {
        try {
            $userType = $this->request->getPost('userType', 'int');
            $data = $this->AppMatch($userType);
            $data = array_map(function ($k,$v){
                return ['id' => $k, 'text' => $v];
            },array_keys($data), array_values($data));
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 获取App信息
     *
     * @param $userType
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by dale  20180823
     */
    public function AppMatch($userType = 0)
    {
        $data = App::getAppMatch($userType);
        $data = array_column($data, 'appName', 'packageName');
        return [0 => '请选择应用'] + $data;
    }


    /**
     * 回复表单
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20180824
     */
    public function replyFormAction()
    {
        try {
            $describle = $this->request->getQuery('describe');
            $this->view->pick('feedback/replyForm');
            Assets::select2();
            Assets::importJs('js/feedback/replyForm.js');
            return $this->view->setVars([
                'templates' => Tool::getValue(Feedback::getTemplateList(), 'data', []),
                'describle' => $describle,
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getDescription(true));
        }
    }

    /**
     * 回复反馈
     *
     * @return mixed|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20171213
     * modify by dale 20180824  回复反馈
     */
    public function replyFeedBackAction()
    {
        if (!UserPower::checkUserPower('App_Feedback_Reply')) {
            return $this->sendErrorResponse(400, '缺少权限');
        }
        try {
            $id = $this->request->getPost('id', 'string');
            $content = $this->request->getPost('content', 'string');
            if (!$id || !$content) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $id = explode(',', $id);
            Feedback::replyFeedback($id, $content);
            return $this->sendSuccessResponse('回复成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 回复模板列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     *
     * create by dale  20180824
     */
    public function templateListAction()
    {
        try {
            $this->view->pick('feedback/templateList');
            Assets::importJs('js/feedback/templateList.js');
            return $this->view->setVars([
                'info' => Tool::getValue(Feedback::getTemplateList(), 'data', [])
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getDescription(true));
        }
    }

    /**
     * 保存模板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180824
     */
    public function saveTemplateAction()
    {
        try {
            $id = $this->request->getPost('id', 'string');
            $content = $this->request->getPost('content', 'string');
            if (!$content) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            Feedback::saveTemplate($content, $id);
            return $this->sendSuccessResponse('保存模板成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 删除模板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180824
     */
    public function delTemplateAction()
    {
        try {
            $id = $this->request->getPost('id');
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            Feedback::delTemplate($id);
            return $this->sendSuccessResponse('删除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 删除反馈列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180824
     */
    public function deleteFeedBackAction()
    {
        if(!UserPower::checkUserPower('App_Feedback_Del')){
            return $this->sendErrorResponse(400,'缺少权限');
        }
        try{
            $ids = $this->request->getPost('ids', 'string');
            if (!is_array($ids)) {
                $ids = explode(',', $ids);
            }
            Feedback::deleteFeedback($ids);
            return $this->sendSuccessResponse('删除成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 屏蔽表单
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180824
     */
    public function shieldFormAction()
    {
        $this->view->pick('feedback/shieldForm');
        Assets::importJs('js/feedback/shieldForm.js');
        return $this->view->setVars([
            
        ]);
    }

    /**
     * 屏蔽用户
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180825
     */
    public function shieldUserAction()
    {
        try {
            if (!UserPower::checkUserPower('App_Feedback_Shield')) {
                return $this->sendErrorResponse(400, '缺少权限');
            }
            $id = $this->request->getPost('id', 'string');
            $reason = $this->request->getPost('reason', 'string');
            $shieldDate = $this->request->getPost('shieldDate', 'string');
            Feedback::shieldUser($id, $shieldDate, $reason);
            return $this->sendSuccessResponse('屏蔽成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 禁言列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20180825
     */
    public function shieldListAction()
    {
        try {
            if (!Power::exist('App_Feedback')) {
                return $this->sendViewError('没有权限');
            }
            $this->view->setTemplateBefore('listForm');
            $this->view->pick('feedback/shieldList');
            Assets::easyUI();
            Assets::importJs('js/feedback/shieldList.js');
            Template::exists('Feedback_Shield', 'list') or die(Main::showMessageModal('Feedback_Shield配置文件不存在，请先创建！', 109106002));
            $listButtonArr = $formButtonArr = $listSearchArr = array();
            if(Power::exist('App_Feedback_Shield')){
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_unShield', 'text' => '解除禁言', 'icon' => 'fa-minus-circle');
            }
            $schools = School::getPower(true);
            if ($schools === true) {
                $schools = School::getSchools();
            }
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_schools', 'data' =>  [0 => '请选择学校'] + $schools, 'default' => '0','style' => 'width:140px;' );
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
            return $this->view->setVars([
                'List'       => Template::createList('list', 'Feedback_Shield', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
                ]),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e instanceof XhException ? $e->getDescription() : $e->getMessage());
        }
    }

    /**
     * 获取屏蔽列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180825
     */
    public function getShieldListAction()
    {
        if (!UserPower::checkUserPower('App_Feedback_Shield')) {
            return $this->sendErrorResponse(400, '缺少权限');
        }
        try {
            $page = $this->request->getPost('page', 'int');
            $rows = $this->request->getPost('rows', 'int');
            $schoolId = $this->request->getPost('schoolId', 'int');
            $userName = $this->request->getPost('userName', 'string');
            $data = Feedback::getShieldList($page, $rows, $schoolId, $userName);
            foreach ($data['rows'] as &$row) {
                $row['createTime'] = date('Y-m-d H:i:s', $row['createTime']/1000);
                $row['endTime'] = date('Y-m-d H:i:s', $row['endTime']/1000);
            }
            return $this->sendJsonResponse($data);
        }catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 解除禁言
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180825
     */
    public function releaseShieldAction()
    {
        try {
            $id = $this->request->getPost('userId', 'int');
            Feedback::releaseShieldUser($id);
            return $this->sendSuccessResponse('解除禁言成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 获取反馈详情
     *
     * create by dale  20180827
     */
    public function feedbackDetailAction()
    {
        try {
            $id = $this->request->getQuery('id', 'string');
            if (!$id) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('feedback/feedbackDetail');
            Assets::viewer();
            Assets::importJs('js/feedback/feedbackDetail.js');
            $row = Feedback::getFeedbackDetail($id);
            $row['createTime'] = date('Y-m-d H:i:s', $row['createTime']/1000);
//            if (isset($row['whetherEnd']) && $row['whetherEnd']) {
//                $row['nowStatus'] = self::$enum['whetherEnd'][$row['whetherEnd']];
//            } else if (isset($row['solveStatus']) && $row['solveStatus']) {
//                $row['nowStatus'] = self::$enum['solveStatus'][$row['solveStatus']];
//            } else if (isset($row['replyStatus']) && $row['replyStatus']) {
//                $row['nowStatus'] = self::$enum['replyStatus'][$row['replyStatus']];
//            } else {
//                $row['nowStatus'] = '';
//            }
//            if ($row['nowStatus'] == '未解决') {
//                $row['nowStatus'] = ;
//            }
            $row['nowStatus'] = self::$enum['replyStatus'][$row['replyStatus']];
            $loginName = XhsysUser::getUserLogonName([ 0 => $row['userId']])[$row['userId']];
            $row['name'] = $row['userName'];
            $row['userName'] =  $row['userName'] .' (' . self::$enum['userType'][$row['userType']] . '-'. $loginName .' )';
            if ($row['forbidStatus']) {
                $row['userName'] =  $row['userName'] .'<i class="fa fa-ban" style="color: red;"></i>';
            }
            $row['userType'] = self::$enum['userType'][$row['userType']];
            if ($row['solveTime']) {
                $row['solveTime'] = date('Y-m-d H:i:s', $row['solveTime']/1000);
            } else {
                $row['solveTime'] = '';
            }
            $row['feedbackType'] = self::$enum['feedbackType'][$row['feedbackType']];
            foreach ($row['replyContent'] as &$contentRow) {
                $contentRow['createTime'] = date('Y-m-d H:i:s', $contentRow['createTime']/1000);
            }
//            var_dump($row);die;
            return $this->view->setVars([
                'info' => $row,
                'power' => [
                    'replyPower' => Power::exist('App_Feedback_Reply'),
                    'delPower' => Power::exist('App_Feedback_Del'),
                    'shieldPower' => Power::exist('App_Feedback_Shield')
                ]
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getMessage());
        }
    }


    /**
     * 批量创建需求
     *
     * create by dale 20171214
     */
//    public function addNeedAction(){
//        $needInfo = $this->request->getJsonRawBody(true);
////        $needInfo =[["id"=>"5a32599c9a2b6f30c4fbc8f1","appName"=>"123","describe"=>"adfadf","schoolId"=>1,"userId"=>1,"packageName"=>"string"]];
////        $needInfo = $this->request->getPost('needInfo');
//        if (!$needInfo){
//            return $this->sendErrorResponse(400,'缺少参数');
//        }
//        try{
//            $this->db->begin();
//            $ids = [];
//            foreach ($needInfo as $index=>$row){
//                $task = XhtrackTask::findFirst([
//                    'conditions' => 'bDelete = 0 AND sFeedbackId = :sFeedbackId:',
//                    'bind'       => ['sFeedbackId' => $row['id']],
//                ]);
//                if (!$task){
//                    $task = new XhtrackTask();
//                }else{
//                    return $this->sendErrorResponse(400,'已经转至需求');
//                }
//                $task->sTaskName       = $row['appName'];
//                $task->sTaskContent    = '<p>'.$row['describe'].'</p>';
//                $task->iTaskType       = 1;
//                $task->sSchoolId       = ','.$row['schoolId'].',';
//                $task->sOfferIds       = ','.$row['userId'].',';
//                $task->sAppName        = $row['appName'];
//                $task->sAppPackage     = $row['packageName'];
//                $task->sFeedbackId     = $row['id'];
//                $task->iOfferUserType  = $row['userType'];
//                $task->tOfferTime      = $row['createTime'];
//                if (!$task->save()){
//                    throw new \Exception('保存失败');
//                }
//                $ids[] = $task->sFeedbackId;
//            }
//            //调接口 告诉状态
//            $postData = [
//                'feedbackIdList' => $ids,
//                'operatorId'     => Main::getLoginUserInfo('userId'),
//                'operatorName'   => Main::getLoginUserInfo('userName'),
//                'solveStatus'    => 1,
//            ];
//            $url = Main::getConfigByName('feedback')['url'];
//            $client = new HttpClient($url);
//            $response = $client->patchJson('api/v1/manage/feedback/demand',$postData);
//            if(!$response->isSuccess()){
////                return $this->showError($response,'调取专职需求接口失败');
//                return $this->sendErrorResponse(500, '调取专职需求接口失败',$response);
////                return $this->sendErrorResponse(500, $response->toArray()['msg'] ?: '调取删除接口失败',$response);
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('转至需求成功');
//        }catch (\Exception $e){
//            $this->db->rollback();
//            return $this->sendErrorResponse(500,$e->getMessage());
//        }
//    }



    /**
     * 获取屏蔽列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20171214
     */
//    public function getShieldListAction(){
//        if(!UserPower::checkUserPower('App_Feedback_Shield')){
//            return $this->sendErrorResponse(400,'缺少权限');
//        }
//        try{
//            $page     = $this->request->getPost('page','int',1);
//            $page -= 1;
//            $pageSize = $this->request->getPost('pageSize','int',10);
//            $url = Main::getConfigByName('feedback')['url'];
//            $client = new HttpClient($url);
//            $response = $client->get('api/v1/manage/feedback/banned/list',['page' => $page,'pageSize' => $pageSize]);
//            if(!$response->isSuccess()){
////                return $this->showError($response,'获取屏蔽列表失败');
//                return $this->sendErrorResponse(500, $response->toArray()['msg'] ?: '获取屏蔽列表失败',$response);
//            }
//            $data = $response->toArray();
//            Tool::runTimestamp($data,['createTime','endTime']);
//
//            return $this->sendJsonResponse($data);
//        }catch (\Exception $e){
//            return $this->sendErrorResponse(500,$e->getMessage());
//        }
//    }

    /**
     * 屏蔽用户
     *
     * create by dale 20171214
     */
//    public function shieldUserAction(){
//        if(!UserPower::checkUserPower('App_Feedback_Shield')){
//            return $this->sendErrorResponse(400,'缺少权限');
//        }
////        $shieldUserInputDTO   = $this->request->getPost('shieldUserInputDTO');
//        $shieldUserInputDTO = $this->request->getJsonRawBody(true);
//        if(!$shieldUserInputDTO){
//            return $this->sendErrorResponse(400,'缺少参数');
//        }
//        $shieldUserInputDTO = array_values(array_column($shieldUserInputDTO,null,'userId'));
//        $postData = [
//            'operatorId'         => Main::getLoginUserInfo('userId'),
//            'operatorName'       => Main::getLoginUserInfo('userName'),
//            'shieldUserInputDTO' => $shieldUserInputDTO,
//        ];
//        $url = Main::getConfigByName('feedback')['url'];
//        $client = new HttpClient($url);
//        $response = $client->postJson('api/v1/manage/feedback/shield',$postData);
//
//        if (!$response->isSuccess()){
////            $err  = $response->toArray();
////            if(isset($err['msg'])){
////                $errMsg = $err['msg'];
////            } else if($err['message']){
////                $errMsg = $err['message'];
////            }else{
////                $errMsg = '接口错误';
////            }
////            return $this->sendErrorResponse(500,$errMsg,json_encode($err));
//            return $this->sendErrorResponse(500, $response->toArray()['msg'] ?: '屏蔽失败',$response);
////            return $this->showError($response,'屏蔽失败');
//        }
//
//        return $this->sendSuccessResponse('屏蔽成功');
//    }





    /**
     *文件上传
     *
     * @return string
     * created by dale 2017/7/5 上午9:39
     */
    public function ajaxTestAction()
    {

        $this->view->disable();
        if(!$this->request->hasFiles()){
            return $this->sendErrorResponse(400,'没有上传文件');
        };
        $files = $this->request->getUploadedFiles();
        $filePath = Main::getConfigByName('appParse');
        $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
        $arr = [];
        foreach ($files as $file){
            $fileName = $file->getName();
            $fullPath = $filePath . $fileName;
            if (!is_writable($filePath)) {
                return $this->sendJsonResponse(['state' =>  $filePath . '缓存无写入权限']);
            }
            $file->moveTo($fullPath);
            $url = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
            @unlink($fullPath);
            $arr[] = $url;
        }
        return json_encode($arr);
    }



    public function ajaxFile(){
        $this->view->disable();
        if(!$this->request->hasFiles()){
            return [];
        };
        $files = $this->request->getUploadedFiles();
        $filePath = Main::getConfigByName('appParse');
        $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
        $arr = [];
        foreach ($files as $file){
            $fileName = $file->getName();
            $fullPath = $filePath . $fileName;
            if (!is_writable($filePath)) {
                return $this->sendJsonResponse(['state' =>  $filePath . '缓存无写入权限']);
            }
            $file->moveTo($fullPath);
            $url = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
            @unlink($fullPath);
            $arr[] = $url;
        }
        return $arr;
    }


    /**
     * 手机端初始化
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180129
     */
    public function getMobileInitAction(){
        $arr = [];
        $url = Main::getConfigByName('feedback')['url'];
        $client = new HttpClient($url);
        $response = $client->get('api/v1/feedback/type');
        if(!$response->isSuccess()){
//            return $this->showError($response,'获取反馈类型失败');

            return $this->sendErrorResponse(500,$response->toArray()['message'] ?: '获取反馈类型失败',$response);
        }
        $arr['feedbackType'] = $response->toArray();
        return $this->sendJsonResponse($arr);
    }

    /**
     * 保存反馈
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180232
     */
    public function saveFeedBackAction(){
        $appName      = $this->request->getPost('appName','string');
        $describe     = $this->request->getPost('describe','string');
        $feedbackType = $this->request->getPost('feedbackType','int');
        $packageName  = $this->request->getPost('packageName','string');
        $telephone    = $this->request->getPost('telephone','string');
        $versionCode  = $this->request->getPost('versionCode','string');
        $versionName  = $this->request->getPost('versionName','string');
        $classId      = $this->request->getPost('classId','string');
        $className    = $this->request->getPost('className','string');
        $userId       = $this->request->getPost('userId','string');
//        if (!$appName || !$describe || !$feedbackType || !$packageName ||
//            !$telephone  ||  !$versionCode || !$versionName ) {
//            return $this->sendErrorResponse(400 , '缺少参数');
//        }
        $image = $this->ajaxFile();
        $user = XhsysUser::findFirst([
            'column'     => 'iSchoolId,sUserName,iUserType',
            'conditions' => 'bDelete = 0  AND iUserId = :iUserId: ',
            'bind'       => ['iUserId' => $userId],
        ]);
        $userType = $user->iUserType;
        $userName = $user->sUserName == '' ? '匿名' : $user->sUserName ;
        if(!$user || !isset($user->iSchoolId)){
            return $this->sendErrorResponse(400,'用户表中未找到该用户或该学校id为空');
        }
        $schoolId     = $user->iSchoolId;
        $schoolName   = XhschoolInfo::getSchoolArray()[$user->iSchoolId];

        $params = [
            'appName'   => $appName,
            'classId'   => $classId,
            'className' => $className,
            'describe'  => $describe,
            'feedbackType' => $feedbackType,
            'image'       => $image,
            'packageName' => $packageName,
            'schoolId'    => $schoolId,
            'schoolName'  => $schoolName,
            'telephone'   => $telephone,
            'userId'      => $userId,
            'userName'    => $userName,
            'userType'    => $userType,
            'versionCode' => $versionCode,
            'versionName' => $versionName
        ];

//        return $this->sendJsonResponse($params);

        $url = Main::getConfigByName('feedback')['url'];
        $client = new HttpClient($url);
        $response = $client->postJson('api/v1/feedback/save',$params);
        if(!$response->isSuccess()){
//            return $this->showError($response,'保存失败');
            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?: '保存失败',$response);
        }
        return $this->sendSuccessResponse('保存成功');

    }

    /**
     * 获取历史用户列表
     *
     *
     * create by dale 20180237
     */
    public function getHistoryListAction(){
        $userId   = $this->request->getPost('userId','int');
        $page     = $this->request->getPost('page','int');
        $pageSize = $this->request->getPost('pageSize','int');

        if(!$userId || (!$page && $page != 0) || !$pageSize ){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $params = [
            'page'    => $page,
            'pageSize'=> $pageSize
        ];
        $url = Main::getConfigByName('feedback')['url'];
        $client = new HttpClient($url);
        $response = $client->get('api/v1/feedback/'.$userId.'/history',$params);
        if(!$response->isSuccess()){
            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?: '获取历史信息失败',$response);
        }
        $data = $response->toArray();
        foreach ($data['data']  as $index =>$value){
            $data['data'][$index]['createTime']   = isset($value['createTime']) ? date('Y-m-d H:i',substr($value['createTime'], 0, 10)) : null;
            $data['data'][$index]['replyStatus']  = isset($this->replyStatus[$value['replyStatus']])   ? $this->replyStatus[$value['replyStatus']]  : null;
            $data['data'][$index]['feedbackType'] = isset($this->feedbackType[$value['feedbackType']]) ? $this->feedbackType[$value['feedbackType']] : null;
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 获取反馈详情
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180237
     */
//    public function feedbackDetailAction(){
//        $userId     = $this->request->getPost('userId','int');
//        $feedbackId = $this->request->getPost('feedbackId','string');
//
//        if(!$userId  || !$feedbackId){
//            return $this->sendErrorResponse(400,'缺少参数');
//        }
//        $params = [
//            'userId'    => $userId,
//        ];
//        $url = Main::getConfigByName('feedback')['url'];
//        $client = new HttpClient($url);
//        $response = $client->get('api/v1/feedback/'.$feedbackId.'/detail',$params);
//        if(!$response->isSuccess()) {
////            return $this->showError($response,'获取信息详情失败');
//            return $this->sendErrorResponse(500, $response->toArray()['msg'] ?: '获取信息详情失败', $response);
//        }
//        $data = $response->toArray();
//        Tool::runTimestamp($data,'createTime');
//        Tool::runTimestamp($data['replyContent'],'createTime');
//        Tool::runEnum($data,['feedbackType'=>$this->feedbackType]);
//        return $this->sendJsonResponse($data);
//    }

    /**
     * 评价
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180239
     */
    public function assessFeedbackAction(){
        $feedbackId = $this->request->getPost('feedbackId','string');
        $assessment = $this->request->getPost('assessment','int');

        if(!$feedbackId || !$assessment){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $params = [
            'assessment'    => $assessment,
        ];
        $url = Main::getConfigByName('feedback')['url'];
        $client = new HttpClient($url);
        $response = $client->get('/api/v1/feedback/assessment/'.$feedbackId,$params);
        if(!$response->isSuccess()) {
//            return $this->showError($response,'调取接口失败');
            return $this->sendErrorResponse(500, $response->toArray()['msg'] ?: '调取接口失败', $response);
        }
        return $this->sendSuccessResponse('评价成功');
    }

    /**
     * 获取区域
     *
     * @param $id
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180257
     */
    public function getAreaAction($id = null){
        if ( !$id ) {
            $arr = Hrm::getDepArray('XHYYB',1);
            $arr = array_column($arr,'text','id');
            $arr[0] = '全部区';
        } else {
            $arr = XhhrmDepart::getDeps($id);
            $arr[0] = '全部市';
        }
        $arr = array_reverse($arr,true);
        return $this->sendJsonResponse($arr);
    }

    /**
     * 获取city
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190110
     */
    public function getCityAction()
    {
        $id = $this->request->getPost('id', 'int');
        $newArr[] = [
            'id' => '0',
            'text' => '全部市'
        ];
        if (!$id) {
            return  $this->sendJsonResponse($newArr);
        }
        $deps = XhhrmDepart::getDeps($id);
        foreach ($deps as $index => $dep) {
            $newArr[] = [
                'id' => $index,
                'text' => $dep
            ];
        }
        return  $this->sendJsonResponse($newArr);
    }


    /**
     * 筛选学校
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190110
     */
    public function filterSchoolAction()
    {
        $area = $this->request->getPost('area');
        $city = $this->request->getPost('city');
        $userId = Main::getLoginUserInfo('userId');

        if(!$area && !$city){  //没有选中区域
            $schools = User::getSchoolPower(true,$userId);
        }else{ //只选中区
            if($area && !$city){
                $areaId = $area;
            }else if ($area && $city) {
                $areaId = $city;
            }
            $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$areaId},%'"; //取第一个
            $staffs = $this->db->fetchOne($staffSql);
            $schools = User::getSchool(true,$staffs['iUserId'],true);
        }
//        $schools[0] = '请选择学校';
//        $schools = array_reverse($schools,true);
        $newArr[] = [
            'id' => 0,
            'text' => '请选择学校'
        ];
        foreach ($schools as $index => $school) {
            $newArr[] = [
                'id' => $index,
                'text' => $school
            ];
        }
        return $this->sendJsonResponse($newArr);
    }

    /**
     * 回复成功页面
     *
     * @return string
     *
     * create by dale  20190122
     */
    public function replySuccessAction()
    {
        try {
            $this->view->pick('feedback/replySuccess');
            Assets::importJs('js/feedback/replySuccess.js');
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 选择回复面板
     *
     * @return string
     *
     * create by dale  20190128
     */
    public function replyChooseAction()
    {
        try {
            $this->view->pick('feedback/replyChoose');
            Assets::importJs('js/feedback/replyChoose.js');
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }


}